/**
 * o(logN)
 */
/* function a(n) {
  let i = 1;
  while (i <= n) {
    i *= 2;
  }
  return i
}

console.log(a(10));  */

/**
 * 快慢指针
 */


/** 
 * 最接近的三数之和
*/
function threeSumClosest(nums, target) {
  //1、 先排序
  // -> <-
  let length = nums.length;
  let res = Number.MAX_SAFE_INTEGER;
  nums.sort((a, b) => a - b);
  for (let i = 0; i < nums.length; i++) {
    // 依次获取其中的元素
    // nums[i] + nums[i+1] + nums[length-1] = targer
    let left = i + 1;
    let right = length - 1
    while (left < right) {
      let sum = nums[i] + nums[left] + nums[right]
      if (Math.abs(sum - target) < Math.abs(res - target)) {
        res = sum;
      }

      if (sum < target) {
        left++
      } else if (sum > target) {
        right--
      } else {
        return sum; // 如果相等，直接返回
      }
    }
  }
  return res
}